﻿import { storeToRefs } from 'pinia'
import { useKeepAliveStore } from '@/store/keepAlive/keepAliveStore'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
const useScrollPosition = (route) => {
  const systemConfigStore = useSystemConfigStore()
  const { systemConfig } = storeToRefs(systemConfigStore)
  const keepAliveStore = useKeepAliveStore()
  // 获取保存的滚动位置数据
  const { scrollPosition } = storeToRefs(keepAliveStore)
  // 获取当前页面的缓存状态是否被开启
  const isKeepAlive = route.meta.keepAlive
  // 当前路由名
  const currentFullPath = route.fullPath
  // 默认返回页面顶部
  const scrollToTop = () => {
    if ((systemConfig.value.isKeepAlive && !isKeepAlive) || !systemConfig.value.isKeepAlive) {
      document.querySelector('.vk-scroll-wrap').scrollTo(0, 0)
    }
  }
  // 页面滚动到记录的位置
  const scrollToPosition = () => {
    // 开启页面状态缓存的情况下，监听事件在此声明周期内开启
    if (systemConfig.value.isKeepAlive && isKeepAlive) {
      let hasRoute = false
      if (scrollPosition.value.length > 0) {
        scrollPosition.value.forEach((item) => {
          if (item.fullPath === currentFullPath) {
            hasRoute = true
            document.querySelector('.vk-scroll-wrap').scrollTo(0, item.savedPosition)
          }
        })
        if (!hasRoute) {
          document.querySelector('.vk-scroll-wrap').scrollTo(0, 0)
        }
      }
    }
  }
  // 在组件挂载到页面后执行
  onMounted(scrollToTop)
  // keep-alive启用时，页面被激活时使用
  onActivated(scrollToPosition)
}
export default useScrollPosition
